// API services for smart park app
import { request } from './request.js'

// Visitor appointment services
export const visitorAppointmentAPI = {
  // Get visitor appointment list
  getAppointmentList(params = {}) {
    return request({
      url: '/api/services/visitor-appointments/',
      method: 'GET',
      data: params
    })
  },
  
  // Get visitor appointment detail
  getAppointmentDetail(id) {
    return request({
      url: `/api/services/visitor-appointments/${id}/`,
      method: 'GET'
    })
  },
  
  // Create visitor appointment
  createAppointment(data) {
    return request({
      url: '/api/services/visitor-appointments/',
      method: 'POST',
      data
    })
  },
  
  // Update visitor appointment
  updateAppointment(id, data) {
    return request({
      url: `/api/services/visitor-appointments/${id}/`,
      method: 'PUT',
      data
    })
  },
  
  // Delete visitor appointment
  deleteAppointment(id) {
    return request({
      url: `/api/services/visitor-appointments/${id}/`,
      method: 'DELETE'
    })
  },
  
  // Get company list for visitor appointments
  getCompanyList(search = '') {
    return request({
      url: '/api/services/companies-for-visitor/',
      method: 'GET',
      data: { search }
    })
  },
  
  // Get current user's visitor appointments
  getMyAppointments(params = {}) {
    return request({
      url: '/api/services/my-visitor-appointments/',
      method: 'GET',
      data: params
    })
  }
}

// 获取送水服务列表
export function getWaterDeliveries(params) {
	return request({
		url: '/api/services/water-deliveries/',
		method: 'GET',
		data: params
	}).then(response => {
		// 检查响应格式是否为Django view格式(含code、message和data字段)
		if (response.code === 200 && response.data && response.data.list) {
			// 转换Django view格式为DRF ViewSet格式
			return response.data.list.map(item => ({
				service_id: item.service_id,
				product_name: item.product_name,
				quantity: parseInt(item.quantity) || 0, 
				unit_price: parseFloat(item.unit_price) || 0,
				total_amount: parseFloat(item.total_amount) || 0,
				expected_delivery_time: item.expected_delivery_time,
				delivery_address: item.delivery_address || '',
				contact_name: item.contact_name || (item.applicant_user_info ? item.applicant_user_info.name : ''),
				contact_phone: item.contact_phone || '',
				application_time: item.application_time,
				status: item.status,
				unit_id: item.unit_id || null
			}));
		}
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	});
}

// 获取当前用户的送水服务列表
export function getCurrentUserWaterDeliveries(params = {}) {
	return request({
		url: '/api/services/my-water-deliveries/',
		method: 'GET',
		data: params
	}).then(response => {
		console.log('getCurrentUserWaterDeliveries response:', JSON.stringify(response, null, 2))
		
		// 检查响应格式是否为Django view格式(含code、message和data字段)
		if (response.code === 200 && response.data && response.data.list) {
			// 转换Django view格式为DRF ViewSet格式
			return response.data.list.map(item => ({
				service_id: item.service_id,
				product_name: item.product_name,
				quantity: parseInt(item.quantity) || 0, 
				unit_price: parseFloat(item.unit_price) || 0,
				total_amount: parseFloat(item.total_amount) || 0,
				expected_delivery_time: item.expected_delivery_time,
				delivery_address: item.delivery_address || '',
				contact_name: item.contact_name || (item.applicant_user_info ? item.applicant_user_info.name : ''),
				contact_phone: item.contact_phone || '',
				application_time: item.application_time,
				status: item.status,
				unit_id: item.unit_id || null
			}));
		}
		
		// 处理错误情况
		if (response.code >= 400) {
			throw {
				message: response.message || '获取数据失败',
				detail: response.detail || response.message || '未知错误'
			};
		}
		
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	}).catch(error => {
		console.error('getCurrentUserWaterDeliveries error:', error)
		// 重新抛出错误，让调用者处理
		throw error;
	});
}

// 申请送水服务
export function createWaterDelivery(data) {
	// 确保数据格式一致
	const formattedData = {
		...data,
		quantity: parseInt(data.quantity) || 0,
		unit_price: parseFloat(data.unit_price) || 0,
		total_amount: parseFloat(data.total_amount) || 0
	};
	
	console.log('准备发送送水服务申请数据:', JSON.stringify(formattedData, null, 2))
	
	return request({
		url: '/api/services/water-deliveries/add/',
		method: 'POST',
		data: formattedData
	}).then(response => {
		console.log('服务器响应的送水服务申请结果:', JSON.stringify(response, null, 2))
		
		// 检查响应格式是否为Django view格式(含code、message和data字段)
		if (response.code === 201 || response.code === 200) {
			// 成功创建
			return response.data || response;
		}
		
		// 处理错误情况
		if (response.code >= 400) {
			throw {
				message: response.message || '创建失败',
				detail: response.detail || response.message || '未知错误'
			};
		}
		
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	});
}

// 获取送水服务详情
export function getWaterDeliveryDetail(id) {
	return request({
		url: `/api/services/water-deliveries/${id}/`,
		method: 'GET'
	}).then(response => {
		// 检查响应格式是否为Django view格式
		if (response.code === 200 && response.data) {
			const item = response.data;
			// 转换为DRF ViewSet格式，确保数字类型字段正确处理
			return {
				service_id: item.service_id,
				product_name: item.product_name,
				quantity: parseInt(item.quantity) || 0,
				unit_price: parseFloat(item.unit_price) || 0,
				total_amount: parseFloat(item.total_amount) || 0,
				expected_delivery_time: item.expected_delivery_time,
				delivery_address: item.delivery_address || '',
				contact_name: item.contact_name || (item.applicant_user_info ? item.applicant_user_info.name : ''),
				contact_phone: item.contact_phone || '',
				application_time: item.application_time,
				status: item.status,
				rating: parseFloat(item.rating) || 0,
				review_content: item.review_content || '',
				unit_id: item.unit_id || null
			};
		}
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	});
}

// 取消送水服务
export function cancelWaterDelivery(id) {
	return request({
		url: `/api/services/water-deliveries/${id}/cancel/`,
		method: 'POST'
	})
}

// 评价送水服务
export function rateWaterDelivery(id, data) {
	return request({
		url: `/api/services/water-deliveries/${id}/rate/`,
		method: 'POST',
		data
	})
}

// 管理员确认送达
export function confirmDelivery(id) {
	return request({
		url: `/api/services/water-deliveries/${id}/confirm_delivery/`,
		method: 'POST'
	})
}

// Export all API services
export default {
  visitorAppointmentAPI
} 

// 保洁预约相关接口
export function getCleaningBookings(params = {}) {
	return request({
	  url: '/api/services/cleaning-bookings/',
	  method: 'get',
	  data: params
	})
}

// 获取当前用户的保洁预约列表
export function getCurrentUserCleaningBookings(params = {}) {
	return request({
	  url: '/api/services/my-cleaning-bookings/',
	  method: 'get',
	  data: params
	})
}
  
export function getCleaningBookingDetail(id) {
	return request({
	  url: `/api/services/cleaning-bookings/${id}/`,
	  method: 'get'
	})
}

// 装修备案相关接口
export function getDecorationApplications(params = {}) {
	return request({
		url: '/api/services/decoration-applications/',
		method: 'get',
		data: params
	})
}

export function getCurrentUserDecorationApplications(params = {}) {
	return request({
		url: '/api/services/my-decoration-applications/',
		method: 'get',
		data: params
	}).then(response => {
		console.log('getCurrentUserDecorationApplications response:', JSON.stringify(response, null, 2))
		
		// 检查响应格式是否为Django view格式(含code、message和data字段)
		if (response.code === 200 && response.data && response.data.list) {
			return response.data.list;
		}
		
		// 处理错误情况
		if (response.code >= 400) {
			throw {
				message: response.message || '获取数据失败',
				detail: response.detail || response.message || '未知错误'
			};
		}
		
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	}).catch(error => {
		console.error('getCurrentUserDecorationApplications error:', error)
		// 重新抛出错误，让调用者处理
		throw error;
	});
}

export function getDecorationApplicationDetail(id) {
	return request({
		url: `/api/services/decoration-applications/${id}/`,
		method: 'get'
	})
}

export function createDecorationApplication(data) {
	return request({
		url: '/api/services/decoration-applications/add/',
		method: 'post',
		data
	}).then(response => {
		console.log('服务器响应的装修备案申请结果:', JSON.stringify(response, null, 2))
		
		// 检查响应格式是否为Django view格式(含code、message和data字段)
		if (response.code === 201 || response.code === 200) {
			// 成功创建
			return response.data || response;
		}
		
		// 处理错误情况
		if (response.code >= 400) {
			throw {
				message: response.message || '创建失败',
				detail: response.detail || response.message || '未知错误'
			};
		}
		
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	});
}

// 设备维保相关接口
export function getDeviceMaintenanceList(params = {}) {
	return request({
		url: '/api/services/device-maintenance/',
		method: 'get',
		data: params
	})
}

// 获取可用设备列表，用于维保申请
export function getAvailableDevices(params = {}) {
	return request({
		url: '/api/assets/available-devices/',
		method: 'get',
		data: params
	}).then(response => {
		console.log('获取可用设备列表响应:', JSON.stringify(response, null, 2))
		
		// 检查响应格式
		if (response.code === 200 && response.data && response.data.list) {
			return response.data.list;
		}
		
		// 处理错误情况
		if (response.code >= 400) {
			throw {
				message: response.message || '获取设备列表失败',
				detail: response.detail || response.message || '未知错误'
			};
		}
		
		// 如果响应已经是标准格式，直接返回
		return response;
	}).catch(error => {
		console.error('获取可用设备列表失败', error)
		// 重新抛出错误，让调用者处理
		throw error;
	});
}

export function getCurrentUserDeviceMaintenanceList(params = {}) {
	return request({
		url: '/api/services/my-device-maintenance/',
		method: 'get',
		data: params
	}).then(response => {
		console.log('getCurrentUserDeviceMaintenanceList response:', JSON.stringify(response, null, 2))
		
		// 检查响应格式是否为Django view格式(含code、message和data字段)
		if (response.code === 200 && response.data && response.data.list) {
			return response.data.list;
		}
		
		// 处理错误情况
		if (response.code >= 400) {
			throw {
				message: response.message || '获取数据失败',
				detail: response.detail || response.message || '未知错误'
			};
		}
		
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	}).catch(error => {
		console.error('getCurrentUserDeviceMaintenanceList error:', error)
		// 重新抛出错误，让调用者处理
		throw error;
	});
}

export function getDeviceMaintenanceDetail(id) {
	return request({
		url: `/api/services/device-maintenance/${id}/`,
		method: 'get'
	})
}

// 获取用户可用单元列表
export function getUserAvailableUnits() {
	return request({
		url: '/api/services/user-available-units/',
		method: 'GET'
	}).then(response => {
		console.log('获取用户可用单元列表响应 (完整数据):', JSON.stringify(response, null, 2))
		
		// 检查响应格式
		if (response.code === 200) {
			console.log('单元列表数据条数:', response.data ? response.data.length : 0)
			return response.data || [];
		}
		
		// 处理错误情况
		if (response.code >= 400) {
			throw {
				message: response.message || '获取单元列表失败',
				detail: response.detail || response.message || '未知错误'
			};
		}
		
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	}).catch(error => {
		console.error('获取用户可用单元列表失败:', error)
		// 出错时返回模拟数据以便UI显示
		return [
			{
				unit_id: 42,
				unit_number: 'W002',
				building_name: '会议中心',
				floor_label: '1层'
			}
		];
	});
}

export function createDeviceMaintenance(data) {
	return request({
		url: '/api/services/device-maintenance/add/',
		method: 'post',
		data
	}).then(response => {
		console.log('服务器响应的设备维保记录创建结果:', JSON.stringify(response, null, 2))
		
		// 检查响应格式是否为Django view格式(含code、message和data字段)
		if (response.code === 201 || response.code === 200) {
			// 成功创建
			return response.data || response;
		}
		
		// 处理错误情况
		if (response.code >= 400) {
			throw {
				message: response.message || '创建失败',
				detail: response.detail || response.message || '未知错误'
			};
		}
		
		// 如果响应已经是DRF ViewSet格式，直接返回
		return response;
	});
}
  
export function createCleaningBooking(data) {
	return request({
	  url: '/api/services/cleaning-bookings/add/',
	  method: 'post',
	  data
	})
}
  
  export function cancelCleaningBooking(id) {
	return request({
	  url: `/api/services/cleaning-bookings/${id}/cancel/`,
	  method: 'post'
	})
  }
  
  export function rateCleaningBooking(id, data) {
	return request({
	  url: `/api/services/cleaning-bookings/${id}/rate/`,
	  method: 'post',
	  data
	})
  }
  
  // 管理员专用接口
  export function updateCleaningBooking(id, data) {
	return request({
	  url: `/api/services/cleaning-bookings/${id}/`,
	  method: 'patch',
	  data
	})
  }
  
  export function completeCleaningBooking(id, data = {}) {
	return request({
	  url: `/api/services/cleaning-bookings/${id}/complete/`,
	  method: 'post',
	  data
	})
  } 

// 问题反馈相关接口
export function getFeedbackList(params = {}) {
	return request({
		url: '/api/notifications/feedbacks/',
		method: 'GET',
		data: params
	})
}

export function submitFeedback(data) {
	return request({
		url: '/api/notifications/feedbacks/create/',
		method: 'POST',
		data
	})
}

export function getFeedbackDetail(id) {
	return request({
		url: `/api/notifications/feedbacks/${id}/`,
		method: 'GET'
	})
}

export function updateFeedback(id, data) {
	return request({
		url: `/api/notifications/feedbacks/${id}/`,
		method: 'PUT',
		data
	})
}

export function deleteFeedback(id) {
	return request({
		url: `/api/notifications/feedbacks/${id}/delete/`,
		method: 'DELETE'
	})
} 